package com.fish.gaiety.gateway.controller.info;

import com.fish.gaiety.gateway.base.GenericResponseBody;
import com.fish.gaiety.gateway.service.GenericPOJOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;
@Slf4j
public abstract class GenericPOJOController<ENTITY, ID, API> {

    abstract protected GenericPOJOService<ENTITY, ID, API> getService();

    @GetMapping("/{id}")
    @GenericResponseBody
    public ResponseEntity<API> getEntityByID(@PathVariable ID id){
        var service = getService();
        return ResponseEntity.ok(service.toAPI(service.findById(id)));
    }

    @PostMapping()
    @GenericResponseBody
    public ResponseEntity<API> create(@RequestBody API api){
        var service = getService();
        return ResponseEntity.ok(
                service.toAPI(
                        service.create(service.toEntity(api))
                )
        );
    }

    @GetMapping()
    @GenericResponseBody
    public ResponseEntity<List<API>> getAllEntity(Principal principal){
        log.info("请求人为：{}", principal.getName());
        var service = getService();
        return ResponseEntity.ok(service
                .findAll()
                    .map(service::toAPI)
                .toList());
    }

    @PatchMapping()
    @GenericResponseBody
    public ResponseEntity<API> update(@RequestBody API api){
        var service = getService();
        return ResponseEntity.ok(service.toAPI(service.toEntity(api)));
    }

    @DeleteMapping("/{id}")
    @GenericResponseBody
    public ResponseEntity<API> delete(@PathVariable ID id){
        var service = getService();
        return ResponseEntity.ok(service.toAPI(service.delete(id)));
    }

}
